package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.UUID;

/**
 * projectName: shf
 *
 * @author: cbc
 * time: 2022/6/13 10:27 周一
 * description:
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {
    @Reference
    private HouseImageService houseImageService;

    private final static String LIST_ACTION = "redirect:/house/";
    private final static String PAGE_UPLOED_SHOW = "house/upload";

    /**
     * 展示图片
     * @param modelMap
     * @param houseId
     * @param type
     * @return
     */
    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(ModelMap modelMap, @PathVariable Long houseId, @PathVariable Long type) {
        modelMap.addAttribute("houseId", houseId);
        modelMap.addAttribute("type", type);
        return PAGE_UPLOED_SHOW;
    }

    /**
     * 上传图片
     * @param houseId
     * @param type
     * @param files
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(
            @PathVariable Long houseId,
            @PathVariable Integer type,
            @RequestParam(value = "file") MultipartFile[] files) throws IOException {
        if (files.length > 0) {
            for (MultipartFile file : files) {
                //生成随机数
                String newFileName = UUID.randomUUID().toString();
                //上传图片
                QiniuUtils.upload2Qiniu(file.getBytes(), newFileName);
                //添加七牛云域名
                String url = "http://rde8ksxen.hn-bkt.clouddn.com/" + newFileName;
                HouseImage houseImage = new HouseImage();
                houseImage.setHouseId(houseId);
                houseImage.setType(type);
                houseImage.setImageUrl(url);
                houseImage.setImageName(file.getOriginalFilename());
                houseImageService.insert(houseImage);
            }
        }
        return Result.ok();
    }

    @GetMapping("/delete/{houseId}/{id}")
    public String delete(
            ModelMap modelMap,
            @PathVariable Long houseId,
            @PathVariable Long id,
            RedirectAttributes redirectAttributes) {
        HouseImage houseImage = houseImageService.getById(id);
        houseImageService.delete(id);
        QiniuUtils.deleteFileFromQiniu(houseImage.getImageUrl());
        return LIST_ACTION + houseId;
    }
}
